import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description: 案例: 表白墙.
 * User: 86187
 * Date: 2022-11-22
 * Time: 15:18
 */

@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    // 这个对象在多个方法中都要使用.
    private final ObjectMapper objectMapper = new ObjectMapper();

    // List用于保存数据. (存放在内存中, 重启服务器就没了...)
    // private final List<Message> list = new ArrayList<>();
    // 数据存在数据库中.

    // 负责让页面获取到数据
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 显式声明响应得格式.
        resp.setContentType("application/json; charset=utf8");
        // 将 list 转成 json 字符串, 并且返回给页面就行了.
        List<Message> messages = null;
        try {
            messages = load();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        resp.getWriter().write(objectMapper.writeValueAsString(messages));
    }

    // 提交数据.
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取到 body 中的数据并解析.
        Message message = objectMapper.readValue(req.getInputStream(),Message.class);
        // 保存 message. 简单的办法就是保存到内存中.
        // list.add(message);

        try {
            save(message); // 数据保存到数据库中.
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 提交成功后 设置状态码.
        resp.setStatus(200);
        System.out.println("提交数据成功: from = " + message.getFrom() +
                ", to = " + message.getTo() + ", message = " + message.getMessage());
    }
    private List<Message> load() throws SQLException {
        // 从数据库加载数据.

        // 1. 先有一个数据源.
        DataSource dataSource = DBUtil.getDataSource();

        // 2. 建立连接 (Connection 是 java.sql包里的)
        Connection connection = dataSource.getConnection();

        // 3. 构造 sql
        String sql = "select * from message";
        PreparedStatement statement = connection.prepareStatement(sql);

        // 4. 执行操作.
        ResultSet resultSet = statement.executeQuery();

        // 5. 遍历结果集合.
        List<Message> messageList = new ArrayList<>();
        while (resultSet.next()) {
            Message message = new Message();

            message.setFrom(resultSet.getString("from"));
            message.setTo(resultSet.getString("to"));
            message.setMessage(resultSet.getString("message"));

            messageList.add(message);
        }

        // 6. 关闭连接.
        statement.close();
        connection.close();

        return messageList;
    }

    private void save(Message message) throws SQLException {
        // 将数据保存到数据库中.

        // 1. 先有一个数据源.
        DataSource dataSource = DBUtil.getDataSource();


        // 2. 建立连接 (Connection 是 java.sql包里的)
        Connection connection = dataSource.getConnection();

        // 3. 构造 sql
        String sql = "insert into message values(?,?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1,message.getFrom());
        statement.setString(2,message.getTo());
        statement.setString(3,message.getMessage());

        // 4. 执行操作.
        int ret = statement.executeUpdate();
        System.out.println("ret = " + ret);

        // 5. 关闭连接.
        statement.close();
        connection.close();
    }
}
